package com.gack.helper.interceptor;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.gack.business.model.Permission;
import com.gack.business.repository.PermissionRepository;

/**
 * 用于做权限验证的拦截器
 * @author ws
 * 2018-5-28
 */
public class PermissionInterceptor implements HandlerInterceptor{

	@Autowired
	private PermissionRepository permissionRepository;
								 
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
		
		String uri = request.getRequestURI();
		String userId = request.getParameter("userId");
		String enterpriseId = request.getParameter("enterpriseId");
		
		if(userId == null || userId.trim().length() == 0){
			return false;
		}
		if(enterpriseId == null || enterpriseId.trim().length() == 0){
			return false;
		}
		
		userId = userId.trim();
		enterpriseId = enterpriseId.trim();
		List<Permission> permissions = permissionRepository.findByUserIdAndEnterpriseId(userId, enterpriseId);
		
		//若请求的uri不被该权限集合所包含，则返回false，禁止接下来的操作；否则，返回true，继续操作
		for(Permission p : permissions){
			if(p.getUrl().equals(uri)){
				return true;
			}
		}
		
		return false;
		
	}
	
	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
		// TODO Auto-generated method stub
		
	}
	
	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
		// TODO Auto-generated method stub
		
	}
	
}
